package com.rbac.utils.commUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

@Component
public class TransactionService {

    @Autowired
    private DataSourceTransactionManager test1TransactionManager;


    public TransactionStatus begin() {
        TransactionStatus transaction = test1TransactionManager.getTransaction(new DefaultTransactionDefinition());
        return transaction;
    }

    public TransactionStatus beginNew() {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus transaction = test1TransactionManager.getTransaction(def);
        return transaction;
    }


    public void commit(TransactionStatus transaction) {
        test1TransactionManager.commit(transaction);
    }


    public void rollback(TransactionStatus transaction) {
        test1TransactionManager.rollback(transaction);
    }

}

/***
 *
 * 使用说明：
 * //====================加载事务====================
 * @Autowired
 * private TransactionService transactionService;
 *
 * //====================开启事务====================
 * TransactionStatus transactionStatus = transactionService.begin();
 *
 * //====================回滚事务====================
 * transactionService.rollback(transactionStatus);
 *
 * //====================提交事务====================
 * transactionService.commit(transactionStatus);
 *
 */

